package com.gxuwz.zjh.mxbbx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.zjh.mxbbx.entity.Limit;
import com.gxuwz.zjh.mxbbx.service.ILimitService;
import org.apache.ibatis.annotations.Param;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhangjiahui
 * @since 2021-03-19
 */
@RestController
@RequestMapping("/mxbbx/limit")
public class LimitController {

    @Autowired
    private ILimitService iLimitService;


    /**
     * 查询全部权限信息
     * @param modelAndView
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @Pointcut
    @RequestMapping(value = "/findLimitAll")
    public ModelAndView findLimitAll(ModelAndView modelAndView, Page page, Integer pageNumber,
                                     @Param("limitId") String limitId,
                                    Integer pid,boolean sess, HttpServletRequest request, HttpServletResponse response) {
        // 可以通过 wrapper 进行筛选!!!
        QueryWrapper<Limit> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("limit_grade");
        // 进行模糊查询!!!
        if(limitId != null && limitId != ""){
            wrapper.like("limit_id", limitId);
            request.getSession().setAttribute("limitId", limitId);
        }else {
            request.getSession().setAttribute("limitId", "");
        }
        // 销毁session中的pid的值
        if(sess == true){
            request.getSession().removeAttribute("pid");
            // 如果进行初始化，则将limit1和limit3中的值清空
            request.getSession().setAttribute("limit1", null);
            request.getSession().setAttribute("limit3", null);
        }

        // 首次查询只显示最高级别的权限
        if(pid == null){
            // 判断session是否存在值
            if(request.getSession().getAttribute("pid") != null){
                // 如果存在获取sessoion中的pid进行查找
                int id = (int) request.getSession().getAttribute("pid");
                wrapper.eq("limit_grade", id);
            }else {
                // 默认查询根权限
                wrapper.eq("limit_grade", -1);
            }
        }else{
            // pid存在进行下级查询，并存放当前pid
            wrapper.eq("limit_grade", pid);
            request.getSession().setAttribute("pid", pid);
        }

        // 查询数据，给seText赋值
        if(pid == null){
            // 判断是否是页面跳转
            if(pageNumber == null){
                // pid为0 且 sess为空，则为首次进入的根权限
                request.getSession().setAttribute("seText", 1);
            }else {
                int seText = (int) request.getSession().getAttribute("seText");
                request.getSession().setAttribute("seText", seText);
            }
        }else {
            // 通过id查询对应的pid，查看是否为-1，否：则为第二级；是：则为第三级
            Limit limit = new Limit();
            limit.setId(pid);
            Limit limit1 = iLimitService.findLimitById(limit);
            if(limit1.getLimitGrade().equals("-1")){
                request.getSession().setAttribute("seText", 2);
                // 存放父级limit,前端显示进入路径
                request.getSession().setAttribute("limit1", limit1);
            }else {
                request.getSession().setAttribute("seText", 3);
                // 存放父级limit,前端显示进入路径
                Limit limit2 = new Limit();
                limit2.setId(Integer.valueOf(limit1.getLimitGrade()));
                Limit limit3 = iLimitService.findLimitById(limit2);
                request.getSession().setAttribute("limit1", limit1);
                request.getSession().setAttribute("limit3", limit3);
            }
        }

        // Current,页码 + Size,每页条数
        if(pageNumber == null){
            page.setCurrent(1);
        }else {
            page.setCurrent((long)pageNumber);
        }
        // 默认每页6行数据！
        page.setSize(6);
        // 调用分页查询方法！!
        IPage<Limit> limitIPage = iLimitService.selectLimitPage(page, wrapper);
        HttpSession session = request.getSession();
        // 存放一个数组用来让foreach遍历
        int[] pagesList = new int[(int)limitIPage.getPages()];
        for(int i=0; i< (int)limitIPage.getPages(); i++){
            pagesList[i] = i+1;
        }
        session.setAttribute("pagesList", pagesList);
        // 存放page，内有当前页数
        session.setAttribute("page", page);
        System.out.println("总条数"+limitIPage.getTotal());
        System.out.println("总页数"+limitIPage.getPages());
        // 存放总页数
        session.setAttribute("pages", (int)limitIPage.getPages());
        List<Limit> limitList = limitIPage.getRecords();
        System.out.println("limitList = "+limitList);
        modelAndView.addObject("limitList", limitList);
        // 判断limitList中的数据是否存在下一级元素
        ArrayList ListStr = new ArrayList(limitList.size());
        for(int i=0; i<limitList.size(); i++){
            int id1 = limitList.get(i).getId();
            Limit limit = new Limit();
            limit.setLimitGrade(String.valueOf(id1));
            if(iLimitService.findLimitByGrades(limit) != 0){
                ListStr.add(i, "Y");
            }else {
                ListStr.add(i, "N");
            }
        }
        modelAndView.addObject("ListStr", ListStr);
        System.out.println("ListStr =" + ListStr);
        modelAndView.setViewName("limit/limit_list");
        return modelAndView;
    }

    /**
     * 跳转进入新增权限界面
     * @param modelAndView
     * @return
     */
    @RequestMapping(value = "/insertLimit")
    public ModelAndView insertLimit(ModelAndView modelAndView) {
        // 存放查询到的全部权限
        List<Limit> limitList = iLimitService.findLimitAll();
        List<Limit> limitList2 = new ArrayList<>(limitList.size());
        for(Limit limit: limitList){
            System.out.println("limit = " + limit);
            if(limit.getLimitGrade().equals("-1")){
                limitList2.add(limit);
            }else {
                Limit limit1 = new Limit();
                limit1.setId(Integer.valueOf(limit.getLimitGrade()));
                limit1 = iLimitService.findLimitById(limit1);
                System.out.println("limit1 = " + limit1);
                if(limit1.getLimitGrade().equals("-1")){
                    limitList2.add(limit);
                }
            }
        }
        modelAndView.addObject("limits", limitList2);

        modelAndView.setViewName("limit/limit_insert");
        return modelAndView;
    }

    /**
     * 添加权限信息
     * @param modelAndView
     * @param limit
     * @return
     */
    @RequestMapping(value = "/addLimit")
    public ModelAndView addLimit(ModelAndView modelAndView, Limit limit, HttpServletRequest request) {
        Limit limit1 = iLimitService.findLimitById(limit);
        if(limit1 == null){
            iLimitService.addLimit(limit);
            request.setAttribute("result1", "addTrue");
        }else {
            request.setAttribute("result1", "addFalse");
        }
        modelAndView.setViewName("limit/limit_list");
        return modelAndView;
    }

    /**
     * 跳转进入批量新增权限界面
     * @param modelAndView
     * @return
     */
    @RequestMapping(value = "/insertLimits")
    public ModelAndView insertLimits(ModelAndView modelAndView) {
        modelAndView.setViewName("limit/limits_insert");
        return modelAndView;
    }

    /**
     * 批量添加权限信息
     * @param modelAndView
     * @param limits
     * @return
     */
    @RequestMapping(value = "/addLimits")
    public ModelAndView addLimits(ModelAndView modelAndView, Limit limits, HttpServletRequest request) {
        String[] limitsId = limits.getLimitId().split(",");
        String[] limitsGrade = limits.getLimitGrade().split(",");
        String[] limitsText = limits.getLimitText().split(",");
        Limit limit = new Limit();
        for(int i=0; i<limitsId.length; i++){
            limit.setLimitId(limitsId[i]);
            limit.setLimitGrade(limitsGrade[i]);
            limit.setLimitText(limitsText[i]);
            Limit limit1 = iLimitService.findLimitById(limit);
            if(limit1 == null){
                iLimitService.addLimit(limit);
                request.setAttribute("result1", "addTrue");
            }else {
                request.setAttribute("result1", "addFalse");
                break;
            }
        }

        modelAndView.setViewName("limit/limit_list");
        return modelAndView;
    }

    /**
     * 跳转进入修改权限界面
     * @param modelAndView
     * @param limitId
     * @return
     */
    @RequestMapping(value = "/updateLimit")
    public ModelAndView updateLimit(ModelAndView modelAndView, String limitId) {
        // 存放查询到的全部权限
        List<Limit> limitList = iLimitService.findLimitAll();
        List<Limit> limitList2 = new ArrayList<>();
        for(Limit limit: limitList){
            System.out.println("limit = " + limit);
            if(limit.getLimitGrade().equals("-1")){
                limitList2.add(limit);
            }else {
                Limit limit1 = new Limit();
                limit1.setId(Integer.valueOf(limit.getLimitGrade()));
                limit1 = iLimitService.findLimitById(limit1);
                System.out.println("limit1 = " + limit1);
                if(limit1.getLimitGrade().equals("-1")){
                    limitList2.add(limit);
                }
            }
        }
        modelAndView.addObject("limits", limitList2);

        Limit limit = new Limit();
        limit.setLimitId(limitId);
        Limit limit1 = iLimitService.findLimitById(limit);
        modelAndView.addObject("limit", limit1);
        modelAndView.setViewName("limit/limit_update");
        return modelAndView;
    }

    /**
     * 修改权限信息
     * @param modelAndView
     * @param limit
     * @return
     */
    @RequestMapping(value = "/editLimit")
    public ModelAndView editLimit(ModelAndView modelAndView, Limit limit, HttpServletRequest request) {
        iLimitService.updateLimitById(limit);
        request.setAttribute("result2", "editTrue");
        modelAndView.setViewName("limit/limit_list");
        return modelAndView;
    }

    /**
     * 删除权限信息
     * @param limitId
     * @return
     */
    @RequestMapping(value = "/deleteLimitById")
    public ModelAndView deleteLimitById(ModelAndView modelAndView, HttpServletRequest request, String limitId) {
        Limit limit = new Limit();
        limit.setLimitId(limitId);
        iLimitService.deleteLimitById(limit);
        request.setAttribute("result3", "deleteTrue");
        modelAndView.setViewName("limit/limit_list");
        return modelAndView;
    }

}
